<template>
  <div class="knowledge-base">
    <!-- 搜索栏 -->
    <div class="search-section">
      <div class="search-container">
        <el-input 
          v-model="searchQuery" 
          placeholder="搜索医疗知识、疾病、症状..." 
          size="large"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
          <template #suffix>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="main-content">
      <!-- 侧边栏 -->
      <div class="sidebar">
        <div class="sidebar-header">
          <h3>知识分类</h3>
        </div>
        <div class="category-list">
          <div 
            v-for="category in categories" 
            :key="category.id"
            class="category-item"
            :class="{ active: selectedCategory === category.id }"
            @click="selectCategory(category.id)"
          >
            <div class="category-icon">{{ category.icon }}</div>
            <div class="category-info">
              <div class="category-name">{{ category.name }}</div>
              <div class="category-count">{{ category.article_count }}篇</div>
            </div>
            <el-icon class="arrow-icon"><ArrowRight /></el-icon>
          </div>
        </div>

        <!-- 热门标签 -->
        <div class="hot-tags">
          <h4>热门标签</h4>
          <div class="tags-container">
            <el-tag 
              v-for="tag in hotTags" 
              :key="tag"
              @click="handleTagClick(tag)"
              class="tag-item"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="content-area">
        <!-- 面包屑导航 -->
        <el-breadcrumb class="breadcrumb" separator="/">
          <el-breadcrumb-item to="/home">首页</el-breadcrumb-item>
          <el-breadcrumb-item>查知识</el-breadcrumb-item>
          <el-breadcrumb-item v-if="selectedCategoryName">{{ selectedCategoryName }}</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 知识文章列表 -->
        <div v-if="!selectedArticle" class="articles-section">
          <div class="section-header">
            <h2>{{ selectedCategoryName || '全部知识' }}</h2>
            <div class="sort-options">
              <el-select v-model="sortBy" placeholder="排序方式" size="small">
                <el-option label="最新发布" value="latest"></el-option>
                <el-option label="最多阅读" value="popular"></el-option>
                <el-option label="最多收藏" value="favorites"></el-option>
              </el-select>
            </div>
          </div>

          <div class="articles-grid" v-loading="loading">
            <div 
              v-for="article in filteredArticles" 
              :key="article.id"
              class="article-card"
              @click="selectArticle(article)"
            >
              <div class="article-image">
                <img :src="article.cover" :alt="article.title" />
                <div class="article-category">{{ article.category }}</div>
              </div>
              <div class="article-content">
                <h3 class="article-title">{{ article.title }}</h3>
                <p class="article-summary">{{ article.summary }}</p>
                <div class="article-meta">
                  <div class="author-info">
                    <img :src="article.author.avatar" :alt="article.author.name" class="author-avatar" />
                    <span class="author-name">{{ article.author.name }}</span>
                  </div>
                  <div class="article-stats">
                    <span class="read-count">{{ article.read_count }}阅读</span>
                    <span class="like-count">{{ article.like_count }}赞</span>
                  </div>
                </div>
                <div class="article-tags">
                  <el-tag 
                    v-for="tag in article.tags" 
                    :key="tag" 
                    size="small"
                    class="article-tag"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination 
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[12, 24, 48]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalArticles"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>

        <!-- 文章详情 -->
        <div v-else class="article-detail">
          <div class="article-header">
            <el-button @click="backToList" type="text" class="back-btn">
              <el-icon><ArrowLeft /></el-icon>返回列表
            </el-button>
            <h1 class="article-title">{{ selectedArticle.title }}</h1>
            <div class="article-info">
              <div class="author-section">
                <img :src="selectedArticle.author.avatar" :alt="selectedArticle.author.name" class="author-avatar" />
                <div class="author-details">
                  <div class="author-name">{{ selectedArticle.author.name }}</div>
                  <div class="author-title">{{ selectedArticle.author.title }}</div>
                </div>
              </div>
              <div class="article-meta">
                <span>发布时间：{{ selectedArticle.publish_date }}</span>
                <span>阅读量：{{ selectedArticle.read_count }}</span>
                <span>点赞：{{ selectedArticle.like_count }}</span>
              </div>
            </div>
          </div>

          <div class="article-body">
            <div v-html="selectedArticle.content" class="article-content"></div>
            
            <!-- 文章操作 -->
            <div class="article-actions">
              <el-button 
                :type="selectedArticle.isLiked ? 'primary' : 'default'"
                @click="toggleLike"
                :icon="selectedArticle.isLiked ? 'heart-filled' : 'heart'"
              >
                {{ selectedArticle.isLiked ? '已赞' : '点赞' }} ({{ selectedArticle.likeCount }})
              </el-button>
              <el-button 
                :type="selectedArticle.isFavorited ? 'warning' : 'default'"
                @click="toggleFavorite"
                :icon="selectedArticle.isFavorited ? 'star-filled' : 'star'"
              >
                {{ selectedArticle.isFavorited ? '已收藏' : '收藏' }}
              </el-button>
              <el-button @click="shareArticle">分享</el-button>
            </div>

            <!-- 相关文章推荐 -->
            <div class="related-articles">
              <h3>相关推荐</h3>
              <div class="related-list">
                <div 
                  v-for="related in relatedArticles" 
                  :key="related.id"
                  class="related-item"
                  @click="selectArticle(related)"
                >
                  <img :src="related.cover" :alt="related.title" class="related-image" />
                  <div class="related-content">
                    <h4 class="related-title">{{ related.title }}</h4>
                    <p class="related-summary">{{ related.summary }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, ArrowRight, ArrowLeft } from '@element-plus/icons-vue'
import request from '@/utils/request'

// 响应式数据
const searchQuery = ref('')
const selectedCategory = ref(null)
const selectedArticle = ref(null)
const sortBy = ref('latest')
const currentPage = ref(1)
const pageSize = ref(12)

// 知识分类数据
const categories = ref([])
const loading = ref(false)

// 热门标签
const hotTags = ref([
  '感冒发烧', '高血压', '糖尿病', '失眠', '减肥',
  '养胃', '护肝', '补钙', '维生素', '免疫力'
])

// 文章数据
const articles = ref([])
const totalArticles = ref(0)

// 计算属性
const selectedCategoryName = computed(() => {
  if (!selectedCategory.value) return ''
  const category = categories.value.find(c => c.id === selectedCategory.value)
  return category ? category.name : ''
})

const filteredArticles = computed(() => {
  let filtered = articles.value
  
  if (selectedCategory.value) {
    filtered = filtered.filter(article => article.categoryId === selectedCategory.value)
  }
  
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(article => 
      article.title.toLowerCase().includes(query) ||
      article.summary.toLowerCase().includes(query) ||
      article.tags.some(tag => tag.toLowerCase().includes(query))
    )
  }
  
  // 排序
  if (sortBy.value === 'popular') {
    filtered.sort((a, b) => b.readCount - a.readCount)
  } else if (sortBy.value === 'favorites') {
    filtered.sort((a, b) => b.likeCount - a.likeCount)
  } else {
    filtered.sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate))
  }
  
  // 更新总数
  totalArticles.value = filtered.length
  
  return filtered
})

const relatedArticles = computed(() => {
  if (!selectedArticle.value) return []
  return articles.value
    .filter(article => 
      article.id !== selectedArticle.value.id && 
      article.categoryId === selectedArticle.value.categoryId
    )
    .slice(0, 3)
})

// 方法
const selectCategory = (categoryId) => {
  selectedCategory.value = selectedCategory.value === categoryId ? null : categoryId
  currentPage.value = 1
  selectedArticle.value = null
  fetchArticles()
}

const selectArticle = (article) => {
  selectedArticle.value = article
  article.readCount++
}

const backToList = () => {
  selectedArticle.value = null
}

const handleSearch = () => {
  if (searchQuery.value.trim()) {
    ElMessage.success(`搜索：${searchQuery.value}`)
    selectedCategory.value = null
    currentPage.value = 1
    fetchArticles()
  }
}

const handleTagClick = (tag) => {
  searchQuery.value = tag
  handleSearch()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchArticles()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchArticles()
}

// API调用方法
async function fetchCategories() {
  try {
    const { data } = await request.get('/api/knowledge/categories/')
    if (data && data.code === 0) {
      categories.value = data.data
    }
  } catch (error) {
    console.error('获取分类失败:', error)
    ElMessage.error('获取分类失败')
  }
}

async function fetchArticles() {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      page_size: pageSize.value,
      sort: sortBy.value
    }
    
    if (selectedCategory.value) {
      params.category_id = selectedCategory.value
    }
    
    if (searchQuery.value) {
      params.search = searchQuery.value
    }
    
    const { data } = await request.get('/api/knowledge/articles/', { params })
    if (data && data.code === 0) {
      articles.value = data.data.articles
      totalArticles.value = data.data.pagination.total
    }
  } catch (error) {
    console.error('获取文章失败:', error)
    ElMessage.error('获取文章失败')
  } finally {
    loading.value = false
  }
}

const toggleLike = () => {
  if (selectedArticle.value) {
    selectedArticle.value.isLiked = !selectedArticle.value.isLiked
    selectedArticle.value.likeCount += selectedArticle.value.isLiked ? 1 : -1
    ElMessage.success(selectedArticle.value.isLiked ? '点赞成功' : '取消点赞')
  }
}

const toggleFavorite = () => {
  if (selectedArticle.value) {
    selectedArticle.value.isFavorited = !selectedArticle.value.isFavorited
    ElMessage.success(selectedArticle.value.isFavorited ? '收藏成功' : '取消收藏')
  }
}

const shareArticle = () => {
  ElMessage.success('分享链接已复制到剪贴板')
}

onMounted(() => {
  // 初始化数据
  fetchCategories()
  fetchArticles()
})
</script>

<style scoped>
.knowledge-base {
  min-height: 100vh;
  background-color: #f8f9fa;
}

/* 搜索区域 */
.search-section {
  background: linear-gradient(135deg, #4CAF50, #45a049);
  padding: 40px 20px;
  text-align: center;
}

.search-container {
  max-width: 600px;
  margin: 0 auto;
}

.search-container .el-input {
  border-radius: 25px;
  overflow: hidden;
}

/* 主体内容 */
.main-content {
  max-width: 1200px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: 280px 1fr;
  gap: 30px;
  padding: 30px 20px;
}

/* 侧边栏 */
.sidebar {
  background: white;
  border-radius: 12px;
  padding: 20px;
  height: fit-content;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  position: sticky;
  top: 20px;
}

.sidebar-header h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.category-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 8px;
}

.category-item:hover {
  background-color: #f5f5f5;
}

.category-item.active {
  background-color: #e8f5e8;
  border-left: 3px solid #4CAF50;
}

.category-icon {
  font-size: 20px;
  margin-right: 12px;
}

.category-info {
  flex: 1;
}

.category-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 2px;
}

.category-count {
  font-size: 12px;
  color: #999;
}

.arrow-icon {
  color: #ccc;
  font-size: 12px;
}

.hot-tags {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.hot-tags h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  cursor: pointer;
  transition: all 0.3s ease;
}

.tag-item:hover {
  background-color: #4CAF50;
  color: white;
  border-color: #4CAF50;
}

/* 内容区域 */
.content-area {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.breadcrumb {
  margin-bottom: 20px;
}

/* 文章列表 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
}

.section-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.articles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.article-card {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  background: white;
}

.article-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0,0,0,0.15);
}

.article-image {
  position: relative;
  height: 180px;
  overflow: hidden;
}

.article-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.article-category {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(76, 175, 80, 0.9);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.article-content {
  padding: 20px;
}

.article-title {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.article-summary {
  margin: 0 0 15px 0;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.article-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-size: 12px;
  color: #999;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
}

.article-stats {
  display: flex;
  gap: 12px;
}

.article-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.article-tag {
  font-size: 11px;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

/* 文章详情 */
.article-detail {
  max-width: 800px;
  margin: 0 auto;
}

.article-header {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.back-btn {
  margin-bottom: 20px;
  color: #4CAF50;
}

.article-detail .article-title {
  font-size: 28px;
  font-weight: 700;
  color: #333;
  line-height: 1.3;
  margin-bottom: 20px;
}

.article-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.author-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-section .author-avatar {
  width: 50px;
  height: 50px;
}

.author-details .author-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.author-details .author-title {
  font-size: 14px;
  color: #666;
}

.article-meta {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #666;
}

.article-body {
  line-height: 1.8;
}

.article-body .article-content {
  padding: 0;
  font-size: 16px;
  color: #333;
}

.article-body .article-content h2 {
  color: #333;
  font-size: 24px;
  margin: 30px 0 15px 0;
}

.article-body .article-content h3 {
  color: #333;
  font-size: 20px;
  margin: 25px 0 10px 0;
}

.article-body .article-content p {
  margin-bottom: 15px;
}

.article-body .article-content ul {
  margin: 15px 0;
  padding-left: 20px;
}

.article-body .article-content li {
  margin-bottom: 8px;
}

.article-actions {
  display: flex;
  gap: 12px;
  margin: 40px 0;
  padding: 20px 0;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}

/* 相关文章 */
.related-articles {
  margin-top: 40px;
}

.related-articles h3 {
  margin-bottom: 20px;
  color: #333;
  font-size: 20px;
}

.related-list {
  display: grid;
  gap: 15px;
}

.related-item {
  display: flex;
  gap: 15px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.related-item:hover {
  background-color: #f8f9fa;
  border-color: #4CAF50;
}

.related-image {
  width: 120px;
  height: 80px;
  object-fit: cover;
  border-radius: 6px;
  flex-shrink: 0;
}

.related-content {
  flex: 1;
}

.related-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  line-height: 1.3;
}

.related-summary {
  margin: 0;
  font-size: 14px;
  color: #666;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    grid-template-columns: 1fr;
    gap: 20px;
    padding: 20px 15px;
  }
  
  .sidebar {
    position: static;
  }
  
  .articles-grid {
    grid-template-columns: 1fr;
  }
  
  .article-info {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .related-item {
    flex-direction: column;
  }
  
  .related-image {
    width: 100%;
    height: 150px;
  }
}
</style>